package com.lovo.middleman.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lovo.middleman.bean.UserBean;
import com.lovo.middleman.bean.UserRoleBean;
import com.lovo.middleman.constant.MessageCode;
import com.lovo.middleman.service.IUserRoleService;
import com.lovo.middleman.service.IUserService;
import com.lovo.middleman.utils.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    IUserService iUserService;

    @Autowired
    IUserRoleService iUserRoleService;


//    @RequestMapping("/login")
//    public UserBean login(String userName, String passWord) {
//        UserBean userBean = iUserService.login(userName, passWord);
//
//        return userBean;
//    }

    @RequestMapping("/login")
    public ResponseResult<UserBean> login(String userName, String passWord) {
        ResponseResult<UserBean> responseResult = new ResponseResult<>();
        try {
            UserBean userBean = iUserService.login(userName, passWord);
            if (userBean==null){
                responseResult.setCode(MessageCode.ACCOUNT_OR_PASSWORD_ERROR.code);
                responseResult.setMessage(MessageCode.ACCOUNT_OR_PASSWORD_ERROR.message);
            }
            responseResult.setData(userBean);
        }catch (Exception e){
            responseResult.setMessage(MessageCode.ERROR.message);
            responseResult.setCode(MessageCode.ERROR.code);
        }
        return responseResult;
    }


    @RequestMapping("/userBeanPage")
    public Page<UserBean> userBeanPage(int curPage,
                                       int pageSize,
                                       String userName) {

        return iUserService.queryPageBeanItem(curPage, pageSize, userName);
    }

    @RequestMapping("/addUserBean")
    public void addUserBean(@RequestBody UserBean userBean, UserRoleBean userRoleBean) {
        iUserService.addUser(userBean);
        iUserRoleService.addUserRole(userRoleBean.getUserId(), userRoleBean.getRoleId());
    }

    @RequestMapping("/deleteUserBean")
    public void deleteUserBean(int userId) {
        iUserService.deleteUser(userId);
        iUserRoleService.deleteUserRole(userId);
    }

    @RequestMapping("/updateUserBean")
    public void updateUserBean(int userId, int[] roleId) {
        iUserService.updateUser(userId, roleId);
    }
}
